package servlet;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import connection.DbConnection;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.StringTokenizer;

import model.EmailingSystem;
import model.PollUserImpl;
import bean.PollUser;


public class CreateUserServlet extends HttpServlet {


	
	/**
	 * 
	 */
	private static final long serialVersionUID = 2566142539284129110L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost (request, response);
	}
	
	public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("GBK");
		
		System.out.println("createUserServlet run");
		
		// Get parameters
		String accessibility = request.getParameter("accessibility");
		String single_generic = request.getParameter("single_generic");
		String username = request.getParameter("username");
		String email = request.getParameter("email");
		String multiple_email = request.getParameter("hidden_email_list");
		
		// Generate password
		String password = Integer.toString((int)(Math.random()*1000000));
		
		// Error checking getting parameters
		System.out.println("accessibility: "+accessibility);
		System.out.println("single_generic: "+single_generic);
		System.out.println("username: "+username);
		System.out.println("single_email: "+email);
		System.out.println("multiple_email: "+multiple_email);
		System.out.println("password: "+password);
		
		// Check user name taken
		PollUser pu = new PollUser();
		pu.setUsername(username);
		if (PollUserImpl.checkUserNameOnly(pu)) {
			request.getSession().setAttribute("CreateUserUsernameTaken", "t");
			request.getSession().setAttribute("UserCreatedSuccess", "f");
			response.sendRedirect("create_user.jsp");
		} else {
			request.getSession().setAttribute("CreateUserUsernameTaken", "f");
			
			// Create single user account
			if (single_generic == null || single_generic.equals("s")) {
				
				System.out.println("Split: single user");
				
				// Set rest of attributes
				pu.setPassword(password);
				pu.setEmail(email);
				pu.setAccessibility(Integer.parseInt(accessibility));
				//pu.setCreateDate(new java.sql.Date(System.currentTimeMillis()));
				pu.setGenericUser(0);
				
				// Error checking
				System.out.println("User username: "+pu.getUsername());
				System.out.println("User pw: "+pu.getPassword());
				System.out.println("User email: "+pu.getEmail());
				System.out.println("User accessibility: "+pu.getAccessibility());
				//System.out.println("User createDate: "+pu.getCreateDate());
				System.out.println("User generic: "+pu.getGenericUser());
				
				// Set expire date if accessibility is poll administrator
				/*
				if (pu.getAccessibility() == 4) {
					Calendar c = Calendar.getInstance();
					c.setTime(new java.sql.Date(System.currentTimeMillis()));
					c.add(Calendar.DATE, +365); // Add a year to create date for expire date
					java.sql.Date expireDate = new java.sql.Date(c.getTime().getTime());
					pu.setExpireDate(expireDate);
					System.out.println("User expireDate: "+pu.getExpireDate());
				}
				*/
				
				
				// Create user
				Connection conn = new DbConnection().getConn();
				String sql = "INSERT INTO PollUser(Username, Password, email, accessibility, genericUser) VALUES ('";
				sql += pu.getUsername()+"', ";
				sql += pu.getPassword()+", '";
				sql += pu.getEmail()+"', ";
				sql += pu.getAccessibility()+", ";
				//sql += pu.getCreateDate()+", ";
				sql += pu.getGenericUser()+")";
				System.out.println("SQL: "+sql);
				try{
					System.out.println(sql);
					PreparedStatement ps = conn.prepareStatement(sql);
					ps.executeQuery();
				}catch(SQLException e){
					System.out.println("Bad SQL: adduserimpl");
				}
				if (PollUserImpl.checkUserNameOnly(pu)) {
					System.out.println("User Created");
				} else {
					System.out.println("Fialed to create");
				}
				
				// Send email
				EmailingSystem.sendAccountEmail(pu);
				
				String success = "f";
				// Session variables
				if (PollUserImpl.checkUserNameOnly(pu)) {
					success = "t";
					//request.getSession().setAttribute("UserCreatedSuccess", "t");
				} /*else {
					request.getSession().setAttribute("UserCreatedSuccess", "f");
				}*/
				
				// Send back page
				response.sendRedirect("create_user.jsp?UserCreatedSuccess="+success);
				
			} else {		
				// Create generic account
				System.out.println("Creating generic account");
				
				// Tokenize multiple_email string
				String [] tokens = multiple_email.split("\\,");
				
				// Set rest of attributes
				pu.setPassword(password);
				pu.setEmail(tokens[0]);
				pu.setAccessibility(Integer.parseInt(accessibility));
				//pu.setCreateDate(new java.sql.Date(System.currentTimeMillis()));
				pu.setGenericUser(1);
				
				// Error checking
				System.out.println("User username: "+pu.getUsername());
				System.out.println("User pw: "+pu.getPassword());
				System.out.println("User email: "+pu.getEmail());
				System.out.println("User accessibility: "+pu.getAccessibility());
				//System.out.println("User createDate: "+pu.getCreateDate());
				System.out.println("User generic: "+pu.getGenericUser());	
				
				// Create user
				Connection conn = new DbConnection().getConn();
				String sql = "INSERT INTO PollUser(Username, Password, email, accessibility, genericUser) VALUES ('";
				sql += pu.getUsername()+"', ";
				sql += pu.getPassword()+", '";
				sql += pu.getEmail()+"', ";
				sql += pu.getAccessibility()+", ";
				//sql += pu.getCreateDate()+", ";
				sql += pu.getGenericUser()+")";
				System.out.println("SQL: "+sql);
				try{
					System.out.println(sql);
					PreparedStatement ps = conn.prepareStatement(sql);
					ps.executeQuery();
				}catch(SQLException e){
					System.out.println("Bad SQL: adduserimpl");
				}
				if (PollUserImpl.checkUserNameOnly(pu)) {
					System.out.println("User Created");
				} else {
					System.out.println("Fialed to create");
				}
				
				// Send email
				EmailingSystem.sendAccountEmailGeneric(pu, tokens);
				
				String success = "f";
				// Session variables
				if (PollUserImpl.checkUserNameOnly(pu)) {
					success = "t";
					//request.getSession().setAttribute("UserCreatedSuccess", "t");
				} /*else {
					request.getSession().setAttribute("UserCreatedSuccess", "f");
				}*/
				
				// Send back page
				response.sendRedirect("create_user.jsp?UserCreatedSuccess="+success);
			}
			
			
		}

		

	}
}
